<template>
  <div class="log-container">
    <!-- 页面头部：标题+筛选栏 -->
    <div class="page-header">
      <el-row :gutter="20" align="middle">
        <el-col>
          <h2>用例执行日志</h2>
        </el-col>
        <el-col :align="`right`">
          <!-- 日志级别筛选 -->
          <el-select
            v-model="logLevel"
            placeholder="筛选日志级别"
            size="small"
            style="width: 160px; margin-right: 10px"
            @change="filterLogs"
          >
            <el-option label="全部日志" value="" />
            <el-option label="成功日志" value="SUCCESS" />
            <el-option label="失败日志" value="ERROR" />
            <el-option label="信息日志" value="INFO" />
          </el-select>
          <!-- 用例ID搜索 -->
          <el-input
            v-model="caseId"
            placeholder="输入用例ID搜索"
            size="small"
            style="width: 180px; margin-right: 10px"
            @keyup.enter="filterLogs"
          />
          <!-- 刷新/清空按钮 -->
          <el-button type="default" size="small" @click="refreshLogs">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
          <el-button type="default" size="small" style="margin-left: 10px" @click="clearLogs">
            <el-icon><Delete /></el-icon> 清空
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 日志内容区域：按时间倒序排列，失败日志标红 -->
    <el-card class="log-card" shadow="hover" style="margin-top: 15px">
      <div class="log-empty" v-if="filteredLogs.length === 0">
        <el-empty description="暂无执行日志，可先去执行用例" />
      </div>
      <div class="log-list" v-else>
        <div
          v-for="(log, index) in filteredLogs"
          :key="index"
          :class="['log-item', `log-level-${log.level.toLowerCase()}`]"
        >
          <!-- 日志时间 -->
          <span class="log-time">{{ log.time }}</span>
          <!-- 用例ID -->
          <span class="log-case-id">[用例ID: {{ log.case_id }}]</span>
          <!-- 日志内容 -->
          <span class="log-content">{{ log.content }}</span>
        </div>
      </div>
    </el-card>

    <!-- 自动刷新开关 -->
    <div class="auto-refresh" style="margin-top: 10px; text-align: right">
      <el-switch
        v-model="autoRefresh"
        active-text="自动刷新(5s)"
        inactive-text="关闭自动刷新"
        @change="toggleAutoRefresh"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElEmpty, ElIcon } from 'element-plus'
import { Refresh, Delete } from '@element-plus/icons-vue'
import request from '@/api/request'

// 筛选条件
const logLevel = ref('') // 日志级别：SUCCESS/ERROR/INFO
const caseId = ref('')   // 用例ID搜索
// 日志数据：原始日志 + 筛选后日志
const rawLogs = ref([])  // 存储所有日志（避免筛选后丢失原始数据）
const filteredLogs = ref([]) // 筛选后的日志（用于页面渲染）
// 自动刷新相关
const autoRefresh = ref(false) // 是否开启自动刷新
let refreshTimer = null // 自动刷新定时器

// 页面挂载时：加载历史日志 + 初始化自动刷新监听
onMounted(() => {
  getLogs() // 加载已有的执行日志
  // 监听自动刷新状态变化：开启时启动定时器，关闭时清除
  watch(autoRefresh, (newVal) => {
    if (newVal) {
      startAutoRefresh()
    } else {
      clearAutoRefresh()
    }
  })
})

// 页面卸载时：清除定时器，避免内存泄漏
onUnmounted(() => {
  clearAutoRefresh()
})

// 1. 获取所有执行日志（对接Django后端日志接口）
const getLogs = async () => {
  try {
    const res = await request.get('/api/logs/list/')
    // 日志按时间倒序排列（最新的在最上面）
    rawLogs.value = res.data.sort((a, b) => new Date(b.time) - new Date(a.time))
    filteredLogs.value = [...rawLogs.value] // 初始筛选后日志 = 原始日志
  } catch (error) {
    ElMessage.error('获取日志失败，请重试')
  }
}

// 2. 筛选日志（按级别/用例ID）
const filterLogs = () => {
  let result = [...rawLogs.value]
  // 按日志级别筛选
  if (logLevel.value) {
    result = result.filter(log => log.level === logLevel.value)
  }
  // 按用例ID筛选（支持模糊匹配，如输入123匹配123、1234等）
  if (caseId.value) {
    const id = caseId.value.trim()
    result = result.filter(log => log.case_id.toString().includes(id))
  }
  filteredLogs.value = result
}

// 3. 刷新日志
const refreshLogs = () => {
  getLogs()
  ElMessage.success('日志已刷新')
}

// 4. 清空日志（对接Django清空日志接口）
const clearLogs = async () => {
  try {
    await request.delete('/api/logs/clear/')
    rawLogs.value = []
    filteredLogs.value = []
    ElMessage.success('日志已清空')
  } catch (error) {
    ElMessage.error('清空日志失败，请重试')
  }
}

// 5. 启动自动刷新（每5秒刷新一次）
const startAutoRefresh = () => {
  clearAutoRefresh() // 先清除旧定时器，避免重复
  refreshTimer = setInterval(() => {
    getLogs()
  }, 5000)
}

// 6. 清除自动刷新定时器
const clearAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}
</script>

<style scoped lang="scss">
.log-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 15px;
  h2 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }
}

.log-card {
  max-height: 600px;
  overflow-y: auto; // 日志过多时滚动
  padding: 20px;
}

.log-list {
  display: flex;
  flex-direction: column;
  gap: 8px; // 日志项之间的间距
}

.log-item {
  padding: 10px 12px;
  border-radius: 6px;
  background-color: #f8f9fa;
  font-size: 14px;
  line-height: 1.5;
  transition: background-color 0.3s;
  &:hover {
    background-color: #f0f2f5;
  }
}

// 不同级别日志的样式：成功绿、失败红、信息蓝
.log-level-success {
  border-left: 4px solid #67c23a;
  .log-content {
    color: #67c23a;
  }
}
.log-level-error {
  border-left: 4px solid #f56c6c;
  .log-content {
    color: #f56c6c;
    font-weight: 500; // 失败日志加粗，更醒目
  }
}
.log-level-info {
  border-left: 4px solid #409eff;
  .log-content {
    color: #409eff;
  }
}

// 日志各部分样式
.log-time {
  color: #909399;
  margin-right: 12px;
}
.log-case-id {
  color: #303133;
  font-weight: 500;
  margin-right: 12px;
}

// 空日志样式
.log-empty {
  padding: 50px 0;
  text-align: center;
}

// 自动刷新开关样式
.auto-refresh {
  font-size: 14px;
  color: #666;
}
</style>